﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Telerik.Web.UI;
using System.Data.Common;

public partial class Admin_Components_Member_PermissionRoleFuntion : System.Web.UI.UserControl
{
    //--------------------------------------New version--------------------------------------
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                SetupForm();
                //LoadTree();
            }
        }
        catch (Exception ex)
        {

            string url = "~/Default.aspx";
            Response.Redirect(url);
            Session["ErrorMessage"] = ex.Message;

        }
    }

    protected void SetupForm()
    {    
        //Load dữ liệu cho các control khi vừa load form        
        //Utils.LoadDataToCombo(cboRole, "Combo_Role", DbType.Int32, 2); 
        string UserName = Session["UserName"].ToString().Trim();
        DBDataContext dtx = LINQUtil.GetDBReadOnly();
        var q = dtx.Combo_Role(UserName);
        cboRole.DataSource = q;
        cboRole.DataTextField = "Name";
        cboRole.DataValueField = "Code";
        cboRole.DataBind();
        cboRole.Items.Insert(0, new RadComboBoxItem());        
        cboRole.SelectedIndex = 0;
        
       
        
    }

    #region LOAD CONTROLS

    
    
    

    #endregion   

    #region ROLEs

    protected void cboRole_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        rtvRoleFunction.Visible = true;
        if (this.cboRole.SelectedValue == "0")
        {
            rtvRoleFunction.Nodes.Clear();
        }
        else
        {
            LoadTree();
        }     
    }

    public void CheckNode(RadTreeNode node, DBDataContext dtx, int roleID, bool checkChild)
    {
        if (node != null)
        {
            node.Checked = true;
            RoleFunction oldRoleFunction = (from rf in dtx.RoleFunctions
                                            where rf.FunctionID == int.Parse(node.Value) && rf.RoleID == roleID
                                            select rf).FirstOrDefault();
            if (oldRoleFunction == null)
            {
                RoleFunction newRoleFunction = new RoleFunction();
                newRoleFunction.RoleID = int.Parse(cboRole.SelectedValue.ToString());
                newRoleFunction.FunctionID = int.Parse(node.Value);
                newRoleFunction.CreatedBy = Session["UserName"].ToString();
                newRoleFunction.CreatedDateTime = DateTime.Now;
                newRoleFunction.LastUpdatedBy = Session["UserName"].ToString();
                newRoleFunction.LastUpdatedDateTime = DateTime.Now;
                newRoleFunction.RowVersion = 0;
                dtx.Insert<RoleFunction>(newRoleFunction);
            }
            if (checkChild)
            {
                foreach (RadTreeNode child in node.Nodes)
                {
                    CheckNode(child, dtx, roleID, checkChild);
                }
            }
            else
            {
                CheckNode(node.ParentNode, dtx, roleID, checkChild);
            }

        }
        else
            return;
    }
    public void UnCheckNode(RadTreeNode node, DBDataContext dtx, int roleID)
    {
        node.Checked = false;

        if (node == null)
        {
            return;
        }
        else
        {
            List<RoleFunction> delRoleFunctions = (from rf in dtx.RoleFunctions
                                                   where rf.RoleID == roleID && rf.FunctionID == int.Parse(node.Value)
                                                   select rf).ToList();
            if (delRoleFunctions.Count > 0)
            {
                foreach (RoleFunction delITem in delRoleFunctions)
                {
                    dtx.Delete<RoleFunction>(delITem);
                }
            }

        }

        foreach (RadTreeNode child in node.Nodes)
        {
            UnCheckNode(child, dtx, roleID);
        }
    }

    protected void rtvRoleFunctionOnNodeCheck(object sender, RadTreeNodeEventArgs e)
    {
        try
        {
            RadTreeNode node = e.Node;
            DBDataContext dtx = LINQUtil.GetDBWriteOnly();
            int roleID = int.Parse(cboRole.SelectedValue.ToString());
            if (node.Checked)
            {
                CheckNode(node, dtx, roleID, true);
                if (node.ParentNode != null)
                {
                    CheckNode(node.ParentNode, dtx, roleID, false);
                }
            }
            else
            {
                UnCheckNode(node, dtx, roleID);
               
            }
            dtx.SubmitChanges();
            JavascriptUtil.LoadMessage(UpdatePanel1, true, "Phân quyền thành công!");
        }
        catch (System.Exception ex)
        {
            //JavascriptUtil.LoadMessage(UpdatePanel1, false, "Phân quyền thất bại!");
            ControlUtil.Log("-----------------------------");
            ControlUtil.Log("Phan quyen nhom");
            ControlUtil.Log(ex.ToString());
            ControlUtil.Log("-----------------------------");
            JavascriptUtil.LoadMessage(UpdatePanel1, false, ex.Message);
        }

        
    }

    public void LoadTree()
    {

        List<TreeViewItem> list = new List<TreeViewItem>();

        DBDataContext db = LINQUtil.GetDBReadOnly();
        List<GetRoleFunctionForComboResult> dt = db.GetRoleFunctionForCombo(int.Parse(cboRole.SelectedValue)).ToList();
        foreach (GetRoleFunctionForComboResult itemResult in dt)
        {
            string parentId = itemResult.ParentId.ToString();
            string value = itemResult.Value.ToString();

            TreeViewItem item = new TreeViewItem();
            item.Text = itemResult.Text;
            item.Value = value;
            if (parentId.Length != 0 && parentId != "0")
            {
                item.ParentId = parentId;
            }
            item.Check = itemResult.Check == 0 ? false : true;

            list.Add(item);
        }

        rtvRoleFunction.DataFieldParentID = "ParentId";
        rtvRoleFunction.DataFieldID = "Value";
        rtvRoleFunction.DataValueField = "Value";
        rtvRoleFunction.DataTextField = "Text";
        RadTreeNodeBinding checkBinding = new RadTreeNodeBinding();
        checkBinding.CheckedField = "Check";
        checkBinding.Checkable = true;

        rtvRoleFunction.DataSource = list;
        rtvRoleFunction.DataBindings.Add(checkBinding);
        rtvRoleFunction.CheckBoxes = true;
        rtvRoleFunction.DataBind();
        if (rtvRoleFunction.Nodes.Count > 0)
        {
            rtvRoleFunction.Nodes[0].Expanded = true;
        }

    }            
    #endregion

}